package cn.ydxiaoshuai.workrecord;

import com.luciad.imageio.webp.WebPReadParam;
import com.luciad.imageio.webp.WebPWriteParam;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author 小帅丶
 * @className WebpSample
 * @Description  webp 转换 示例代码
 * @Date 2021-07-08-15:55
 **/
@Slf4j
public class WebpSample {

    /**
     * @Author 小帅丶
     * @Description 图片转换为webp
     * @Date  2021-07-08 17:35
     * @param inputStream - 文件流
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage ImageToWebpBufferedImage(InputStream inputStream) {
        try {
            InputStream webpInputStream = ImageToWebpInputStream(inputStream);
            BufferedImage imageTarget = ImageIO.read(webpInputStream);
            return imageTarget;
        }catch (Exception e){
            log.info("ImageToWebpBufferedImage() 出错了 {}",e.getMessage());
            return null;
        }
    }

    /**
     * @Author 小帅丶
     * @Description 图片转换为webp
     * @Date  2021-07-08 17:35
     * @param filePath - 图片本地路径
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage ImageToWebpBufferedImage(String filePath) {
        try {
            InputStream inputStream = new FileInputStream(filePath);
            BufferedImage imageTarget = ImageIO.read(inputStream);
            return imageTarget;
        }catch (Exception e){
            log.info("ImageToWebpBufferedImage() 出错了 {}",e.getMessage());
            return null;
        }
    }

    /**
     * @Author 小帅丶
     * @Description 图片转换为webp
     * @Date  2021-07-08 17:35
     * @param filePath - 图片本地路径
     * @return InputStream
     **/
    public static InputStream ImageToWebpInputStream(String filePath) {
        try {
            InputStream inputStream = new FileInputStream(filePath);
            InputStream webpInputStream = ImageToWebpInputStream(inputStream);
            return webpInputStream;
        }catch (Exception e){
            log.info("ImageToWebpInputStream() 出错了 {}",e.getMessage());
            return null;
        }
    }
    /**
     * @Author 小帅丶
     * @Description 图片转换为webp
     * @Date  2021-07-08 17:35
     * @param inputStream - 文件流
     * @return InputStream
     **/
    public static InputStream ImageToWebpInputStream(InputStream inputStream){
        ByteArrayInputStream bais;
        ByteArrayOutputStream baos;
        try {
            BufferedImage image = ImageIO.read(inputStream);
            baos = new ByteArrayOutputStream();
            // 获取WebpImageWriter实例
            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
            // 配置编码参数
            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
            writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);
            ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
            // 配置ImageWriter输出
            writer.setOutput(ios);
            // Encode
            writer.write(null,
                    new IIOImage(image,
                            null,
                            null),
                    writeParam);
            bais = new ByteArrayInputStream(ImageOutputStreamConvertBytes(ios));
            bais.close();
            baos.close();
            return bais;
        }catch (Exception e){
            log.info("ImageToWebp() 出错了 {}",e.getMessage());
            return null;
        }
    }
    /**
     * @Author 小帅丶
     * @Description webp转换为图片
     * @Date  2021年7月8日17:39:07
     * @param filePath - webp图片本地路径
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage WebpToImage(String filePath) {
       try {
           // 获取WebpImageWriter实例
           ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

           // 配置编码参数
           WebPReadParam readParam = new WebPReadParam();
           readParam.setBypassFiltering(true);

           // 配置ImageReader输入
           reader.setInput(new FileImageInputStream(new File(filePath)));

           // 解码图片
           BufferedImage image = reader.read(0, readParam);

           return image;
       }catch (Exception e){
           log.info("WebpToImage() 出错了 {}",e.getMessage());
           return null;
       }
    }
    /**
     * @Author 小帅丶
     * @Description webp转换为图片
     * @Date  2021年7月8日17:39:07
     * @param inputStream - webp文件路径
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage WebpToImage(InputStream inputStream) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(inputStream2byte(inputStream));
            // 获取WebpImageWriter实例
            ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

            // 配置编码参数
            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);

            ImageInputStream iis = ImageIO.createImageInputStream(bais);
            // 配置ImageReader输入
            reader.setInput(iis);

            // 解码图片
            BufferedImage image = reader.read(0, readParam);

            return image;
        }catch (Exception e){
            log.info("WebpToImage() 出错了 {}",e.getMessage());
            return null;
        }
    }

    /**
     * @Author 小帅丶
     * @Description webp转换为图片
     * @Date  2021年7月8日17:39:07
     * @param filePath - webp文件路径
     * @return java.awt.image.BufferedImage
     **/
    public static InputStream WebpToImageInputStream(String filePath) {
        try {
            BufferedImage bufferedImage = WebpToImage(filePath);
            InputStream inputStreamWebp = bufferedImageToInputStream(bufferedImage);
            return inputStreamWebp;
        }catch (Exception e){
            log.info("WebpToImageInputStream() 出错了 {}",e.getMessage());
            return null;
        }
    }

    /**
     * @Author 小帅丶
     * @Description webp转换为图片
     * @Date  2021年7月8日17:39:07
     * @param inputStream - webp文件流
     * @return java.awt.image.BufferedImage
     **/
    public static InputStream WebpToImageInputStream(InputStream inputStream) {
        try {
            BufferedImage bufferedImage = WebpToImage(inputStream);
            InputStream inputStreamWebp = bufferedImageToInputStream(bufferedImage);
            return inputStreamWebp;
        }catch (Exception e){
            log.info("WebpToImageInputStream() 出错了 {}",e.getMessage());
            return null;
        }
    }
    /**
     * @Author 小帅丶
     * @Description ImageOutputStream转换为Bytes
     * @Date  2021-07-08 17:31
     * @param ios - ImageOutputStream
     * @return byte[]
     **/
    public static byte[] ImageOutputStreamConvertBytes(ImageOutputStream ios) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(255);
        long counter = 0;
        try {
            System.out.println("getStreamPosition()[BEFORE]=" + ios.getStreamPosition());
            ios.seek(0);
            System.out.println("getStreamPosition()[AFTER]=" + ios.getStreamPosition());
        } catch (IOException e) {
            log.info("ImageOutputStreamConvertBytes() 出错了 {}", e.getMessage());
        }
        while (true) {
            try {
                bos.write(ios.readByte());
                counter++;
            } catch (EOFException e) {
                System.out.println("End of Image Stream;"+e.getMessage());
                break;
            } catch (IOException e) {
                System.out.println("Error processing the Image Stream;"+e.getMessage());
                break;
            }
        }
        System.out.println("Total bytes read =" + counter);
        byte[] retValue = bos.toByteArray();
        return retValue;
    }
    /**
     * 将InputStream转换为byte
     * @param inStream - 文件流
     * @return byte[]
     */
    public static byte[] inputStream2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    /**
     * 将BufferedImage转换为InputStream
     * @param image - bufferedimage对象
     * @return InputStream
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (Exception e) {
            log.info("bufferedImageToInputStream() 出错了:{}",e.getMessage());
        }
        return null;
    }

}
